package cn.edu.gzmtu.controller;

import cn.edu.gzmtu.domain.Permission;
import cn.edu.gzmtu.domain.Role;
import cn.edu.gzmtu.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.Arrays;
import java.util.List;


@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    /**
     * 查询所有角色信息
     */
    @RequestMapping("/findAll.do")
    @RolesAllowed({"ADMIN"})
    public ModelAndView findAll() throws Exception {

        List<Role> roleList = roleService.findAll();

        ModelAndView mv = new ModelAndView();
        mv.addObject("roleList", roleList);
        mv.setViewName("role-list");

        return mv;
    }

    /**
     * 添加角色
     *
     * @param role
     * @return
     * @throws Exception
     */
    @RequestMapping("/save.do")
    public String save(Role role) throws Exception {

        roleService.save(role);

        return "redirect:findAll.do";
    }

    /**
     * （1）查询角色
     * （2）查询角色未具有的权限
     *
     * @param id
     * @return
     */
    @RequestMapping("/findRoleByIdAndAllPermission.do")
    public ModelAndView findRoleByIdAndAllPermission(String id) throws Exception {

        // 根据roleId查询角色
        Role role = roleService.findById(id);

        // 查询用户不具有的权限（可以添加的权限）
        List<Permission> permissionList = roleService.findRoleOtherPermission(id);

        ModelAndView mv = new ModelAndView();
        mv.addObject("role", role);
        mv.addObject("permissionList", permissionList);
        mv.setViewName("role-permission-add");

        return mv;
    }

    /**
     * 为角色添加权限
     *
     * @param roleId
     * @param permissionIds
     */
    @RequestMapping("/addPermissionToRole.do")
    public String addPermissionToRole(@RequestParam(name = "roleId") String roleId, @RequestParam(name = "ids") String[] permissionIds) throws Exception {

        roleService.addPermissionToRole(roleId, permissionIds);

        return "redirect:findAll.do";
    }

}
